package com.tinckay.controller;

import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.tinckay.common.annotation.Log;
import com.tinckay.common.constant.LogType;
import com.tinckay.common.constant.ResultEnum;
import com.tinckay.common.log.LogManager;
import com.tinckay.common.log.factory.LogTaskFactory;
import com.tinckay.common.util.HttpContextUtils;
import com.tinckay.common.util.IPUtils;
import com.tinckay.common.util.MD5Utils;
import com.tinckay.common.util.ShiroUtils;
import com.tinckay.entity.form.LoginForm;
import io.swagger.annotations.Api;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @Author: Jean
 * @Desc:
 * @Date: 2018/10/23 14:02
 */
@Api(tags = "登陆模块")
@RestController
public class LoginController extends ApiController {

    @Log(value = "登陆", logType = LogType.LOGIN)
    @PostMapping("/login")
    public R login(@RequestBody @Validated LoginForm loginForm) {

        String username = loginForm.getUsername();
        String password = MD5Utils.encrypt(username, loginForm.getPassword());
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            ShiroUtils.login(token);
            return success(ShiroUtils.getCurrentUser());
        } catch (UnknownAccountException | IncorrectCredentialsException | LockedAccountException e) {
            return failed(e.getMessage());
        } catch (AuthenticationException e) {
            return failed("认证失败");
        }
    }

    @GetMapping("/logout")
    public R logout() {
        LogManager
                .me()
                .executeLog(LogTaskFactory.sysLog(LogType.EXIT,
                        ShiroUtils.getCurrentUser(),
                        "退出",
                        0L,
                        "com.tinckay.controller.LoginController.logout()",
                        null,
                        IPUtils.getIpAddr(HttpContextUtils.getHttpServletRequest())));

        ShiroUtils.getSubject().logout();
        return success(null);
    }

    /**
     * 未认证
     *
     * @return
     */
    @ApiIgnore
    @GetMapping("/401")
    public R unauthorized() {
        return failed(ResultEnum.UNAUTHORIZED);
    }

    /**
     * 没有操作权限状态码
     *
     * @return
     */
    @ApiIgnore
    @GetMapping("/403")
    public R unauthenticated() {
        return failed(ResultEnum.FORBIDDEN);
    }

}
